package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.text.RelativeDateTimeFormatter;
import android.net.wifi.ScanResult;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.RetrofitService;
import com.smcdd.cdb.dbo.cdb_dbo.network.RetrofitWifi;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.HttpUtil;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IWifiAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.CdbListInfoActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.WifiActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.WifiAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.Encode;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.WifiAdmin;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.AwaitDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.HintDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.ListDialog;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.smcdd.cdb.dbo.cdb_dbo.R.string.user_name;

/**
 * 作者：Administrator on 2017/6/23 16:09
 * 邮箱：zhanghuaiha@gmail.com
 */

public class WifiPresenter extends BasePresenter<IWifiAc> {

    private WifiAdmin mWifiAdmin;
    private WifiAdapter wifiAdapter;
    private List<ScanResult> mWifiList;
    private List<ScanResult> mList;
    static final int WIFICIPHER_NOPASS = 1;
    static final int WIFICIPHER_WEP = 2;
    static final int WIFICIPHER_WPA = 3;
    private SelectPicPopupWindow menuWindow;
    private String mac;
    private String ver;
    private HttpUtil httpUtil;
    private WifiActivity wifiAc;
    private ListDialog listDialog;
    private EditText user;
    private Dialog progressDialog;
    private HintDialog selfDialog;

    public WifiPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(){
        mWifiAdmin = new WifiAdmin(mContext);
        wifiAc = getView().getWifiAc();
        setAdapter();
        loadData();
    }

    public void removeWifi(String ssid){
        if (!ssid.equals("")) {
            mWifiAdmin.removeWifi(ssid);
        }
    }

    private void setAdapter() {
        wifiAdapter = new WifiAdapter(mContext);
        getView().getRecycler().setAdapter(wifiAdapter);
        wifiAdapter.setItemClickListenter((scanResult, position) -> {
           // wifiAc.Dialog("正在链接：\r\n"+scanResult.SSID+"\r\nwifi，请等待.");
            Dialogs("正在链接wifi：\r\n"+scanResult.SSID+"\r\n请等待.");
            int capa = getCapa(scanResult.capabilities);
            if (capa == WIFICIPHER_NOPASS) {
                mWifiAdmin.addNetwork(mWifiAdmin.CreateWifiInfo(scanResult.SSID,null, WIFICIPHER_NOPASS));
            }else {
                AlertDialog.Builder alert=new AlertDialog.Builder(mContext);
                alert.setTitle(scanResult.SSID);
                alert.setMessage("输入密码");
                final EditText et_password=new EditText(mContext);
                final SharedPreferences preferences=mContext.getSharedPreferences("wifi_password", Context.MODE_PRIVATE);
                et_password.setText(preferences.getString(scanResult.SSID, ""));
                alert.setView(et_password);
                alert.setPositiveButton("连接", (dialog, which) -> {
                    String pw = et_password.getText().toString();
                    if(null == pw  || pw.length() < 8){
                        Toast.makeText(mContext, "密码至少8位", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    SharedPreferences.Editor editor=preferences.edit();
                    editor.putString(scanResult.SSID, pw);
                    editor.commit();
                    mWifiAdmin.addNetwork(mWifiAdmin.CreateWifiInfo(scanResult.SSID, et_password.getText().toString(), 3));
                });
                alert.setNegativeButton("取消",(dialog, which) -> {

                });
                alert.create();
                alert.show();
            }
        });
    }

    public void loadData() {
        mWifiAdmin.startScan(mContext);
        mWifiList =mWifiAdmin.getWifiList();
        mList = new ArrayList<>();
        for (int i = 0; i < mWifiList.size(); i++) {
            if (mWifiList.get(i).SSID.contains("ChongDianDian")) {
                mList.add(mWifiList.get(i));
            }
        }
        wifiAdapter.addData(mList);
        wifiAdapter.Dialog();
    }

    public void getMac2Ver(){
        httpUtil = new HttpUtil();
        String url = "http://192.168.4.1/sta_para.js#";
        httpUtil.getJson(url, new HttpUtil.HttpCallBack() {
            @Override
            public void onSusscess(String data) {
                String js = data.replaceAll("\'", "");
                String mac_ver = js.substring(js.indexOf("mac"), js.length() - 2);
                mac = mac_ver.substring(mac_ver.indexOf(":"), mac_ver.indexOf(",")).substring(1);
                ver = mac_ver.substring(mac_ver.lastIndexOf(":"), mac_ver.length()).substring(1);
                Log.e("WifiPresenter",mac+"!!!ver:"+ver);
            }
            @Override
            public void onError(String meg) {
                Log.e("WifiPresenter","xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            }
        });
    }

    private void uploadingMac_Ver(String user,String pws){
        String url = "http://192.168.4.1/wifi_set.html";
        Log.e("WifiPresenter","name:"+user+"====passwrold:"+pws);
        RetrofitService apiFactory = RetrofitWifi.INSTANCE.getRetrofit().create(RetrofitService.class);
        apiFactory.UploadingMac_Ver(user,pws,mac,ver).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.e("WifiPresenter","success");
                ToastUtil.showToast("WiFi配置信息已发出，设备正在重启\r\n请注意设备指示灯变化");
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.e("WifiPresenter","error");
                ToastUtil.showToast("WiFi配置信息已发出，设备正在重启\r\n请注意设备指示灯变化");
            }
        });
    }

    /**
     * 判断当前wifi加密状态
     * @param capabilities
     * @return
     */
    public int getCapa(String capabilities){
        if (capabilities.contains("WPA") || capabilities.contains("wpa")) {
            Log.i("river", "wpa");
            return WIFICIPHER_WPA;

        } else if (capabilities.contains("WEP") || capabilities.contains("wep")) {
            Log.i("river", "wep");
            return WIFICIPHER_WEP;
        } else {
            Log.i("river", "no");
            return WIFICIPHER_NOPASS;
        }
    }


    /*
      PopupWindow展示
      */
    public void selectImgs(String ssid) {

        ((InputMethodManager) wifiAc.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(wifiAc.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(wifiAc) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) wifiAc.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_wifi_popupwindows, null);

                TextView name = (TextView) menuview.findViewById(R.id.wifi_popup_name);
                TextView search = (TextView) menuview.findViewById(R.id.wifi_popup_search);
                user = (EditText) menuview.findViewById(R.id.wifi_popup_user);
                EditText pws = (EditText) menuview.findViewById(R.id.wifi_popup_pws);
                Button en = (Button) menuview.findViewById(R.id.wifi_popup_en);
                String userName1 = App.SP.getString("userName", "");
                String pwsString1 = App.SP.getString("pwsString", "");
                user.setText(userName1);
                pws.setText(pwsString1);

                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */

                search.setOnClickListener(v -> {
                    Dialog();
                });

                name.setText("当前已连接的wifi:"+ssid);

                en.setOnClickListener(v ->  {
                    String userString = user.getText().toString().trim();
//                    String userName = Encode.toURLEncoded(userString);
                    String pwsString = pws.getText().toString().trim();
                    Log.e("WifiPresenter",userString+"!!!"+pwsString);
                    uploadingMac_Ver(userString,pwsString);
                    App.EDIT.putString("userName",userString);
                    App.EDIT.putString("pwsString",pwsString);
                    App.EDIT.commit();
                    dismiss();
                });
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(wifiAc.findViewById(R.id.wifi), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }


    public void Dialog() {
        mWifiAdmin.startScan(mContext);
        List<ScanResult> wifiList = mWifiAdmin.getWifiList();
        listDialog = new ListDialog(mContext,wifiList);
        listDialog.show();
      //  listDialog.setDate(wifiList);
        listDialog.setItemClickListenter((scan, position) -> {
            user.setText(scan.SSID);
            listDialog.dismiss();
        });
    }

    private void Dialogs(String a) {
        selfDialog = new HintDialog(mContext);
        selfDialog.setTitle("提示");
        selfDialog.setMessage(a);
        selfDialog.show();
    }
}
